package com.squapsource.project_euler;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class Problem11 {

	/**
	 * @param args
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	public static void main(String[] args) throws URISyntaxException,
			IOException {

		File gridFile = new File(Problem11.class.getResource(
				"/Problem11Grid.txt").toURI());

		String gridString = FileUtils.readFileToString(gridFile);
		int[][] grid = getGridArray(gridString);
		int maxProduct = getMaxAdjacentProduct(grid);
		System.out.println(maxProduct);
	}

	private static int getMaxAdjacentProduct(int[][] grid) {
		int max = 0;
		for (int i = 0; i < 20; i++) {
			for (int j = 0; j < 20; j++) {
				//Right
				if (j + 3 < 20)
					max = testMax(max, grid[i][j], grid[i][j + 1],
							grid[i][j + 2], grid[i][j + 3]);
				//Down and Right
				if (j + 3 < 20 && i + 3 < 20)
					max = testMax(max, grid[i][j], grid[i + 1][j + 1],
							grid[i + 2][j + 2], grid[i + 3][j + 3]);
				//Down
				if (i + 3 < 20)
					max = testMax(max, grid[i][j], grid[i + 1][j],
							grid[i + 2][j], grid[i + 3][j]);
				//Down and Left
				if (j - 3 >= 0 && i + 3 < 20)
					max = testMax(max, grid[i][j], grid[i + 1][j - 1],
							grid[i + 2][j - 2], grid[i + 3][j - 3]);
				//Left
				if (j - 3 >= 0)
					max = testMax(max, grid[i][j], grid[i][j - 1],
							grid[i][j - 2], grid[i][j - 3]);
				//Up and Left
				if (j - 3 >= 0 && i - 3 >= 0)
					max = testMax(max, grid[i][j], grid[i - 1][j - 1],
							grid[i - 2][j - 2], grid[i - 3][j - 3]);
				//Up
				if (i - 3 >= 0)
					max = testMax(max, grid[i][j], grid[i - 1][j],
							grid[i - 2][j], grid[i - 3][j]);
				//Up and Right
				if (j + 3 < 20 && i - 3 >= 0)
					max = testMax(max, grid[i][j], grid[i - 1][j + 1],
							grid[i - 2][j + 2], grid[i - 3][j + 3]);
			}

		}

		return max;
	}

	private static int testMax(int max, int i, int j, int k, int l) {
		if (i * j * k * l > max)
			return i * j * k * l;
		return max;
	}

	private static int[][] getGridArray(String gridString) {
		int[][] gridArray = new int[20][20];
		List<String> lines = Arrays.asList(gridString.split("\n"));
		for (int i = 0; i < 20; i++) {
			List<String> cells = Arrays.asList(lines.get(i).split(" "));
			for (int j = 0; j < 20; j++) {
				gridArray[i][j] = Integer.parseInt(cells.get(j));
			}

		}
		return gridArray;
	}

}
